<template>
  <div class="page-container">
    <el-form
      ref="dataForm"
      label-width="100px"
      :model="formData"
      class="fit-box full-height"
      :rules="rules"
    >
      <el-tabs v-model="tabName" class="fit-box full-height">
        <el-tab-pane name="table" label="基础信息" class="fit-box full-height">
          <el-row style="margin-top: 10px;">
            <el-col :span="4">
              <el-form-item label="表格名称" prop="name">
                <el-input v-model="formData.name" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="分页大小" prop="defaultPageSize">
                <ac-select v-model="formData.defaultPageSize" options="20,50,100,200" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="显示表头" prop="showHeader">
                <ac-dict-switch v-model="formData.showHeader" dictCode="dictYesNo" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="显示表头调整" prop="showHeaderSetting">
                <ac-dict-switch v-model="formData.showHeaderSetting" dictCode="dictYesNo" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="显示全屏按钮" prop="showFull">
                <ac-dict-switch v-model="formData.showFull" dictCode="dictYesNo" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="显示复选框" prop="showCheckbox">
                <ac-dict-switch v-model="formData.showCheckbox" dictCode="dictYesNo" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">
              <el-form-item label="显示序号" prop="showOrdinal">
                <ac-dict-switch v-model="formData.showOrdinal" dictCode="dictYesNo" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="显示操作列" prop="showOperate">
                <ac-dict-switch v-model="formData.showOperate" dictCode="dictYesNo" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="显示页码栏" prop="showPagination">
                <ac-dict-switch v-model="formData.showPagination" dictCode="dictYesNo" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="显示边框" prop="showBorder">
                <ac-dict-switch v-model="formData.showBorder" dictCode="dictYesNo" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="合计栏设置" prop="totalJson">
                <ac-icon
                  iconId="018ece4f712124866f78"
                  size="18"
                  style="cursor: pointer"
                  @click="showTotalDialog"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4" style="text-align: right;align-content: center;">
              <el-button
                v-if="!sortFieldInst && (formData.fieldList || []).length > 1"
                type="primary"
                @click="sortDataField"
              >开启排序</el-button>
              <el-button
                v-else-if="(formData.fieldList || []).length > 1"
                type="info"
                @click="unSortDataField"
              >关闭排序</el-button>
              <el-button
                type="success"
                @click="addField"
              >添加字段</el-button>
            </el-col>
          </el-row>
          <div class="fit-box full-height">
            <el-table
              ref="sortFieldTable"
              :show-overflow-tooltip="false"
              tooltip-effect="light"
              class="field-table fit-table edit-table"
              width="100%"
              :data="formData.fieldList"
              :row-key="getFieldRowKey"
              :border="true"
              :stripe="false"
            >
              <el-table-column
                header-align="center"
                align="center"
                label="字段名称"
                :min-width="120"
                prop="fieldName"
              />
              <el-table-column
                header-align="center"
                label="显示名称"
                :min-width="120"
                prop="aliasName"
              >
                <template #default="scope">
                  <el-input v-model="scope.row.aliasName" />
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                label="列宽"
                width="120"
                prop="width"
              >
                <template #header>
                  <el-tooltip>
                    <template #content>
                      <div>0时为自动宽度,负数时为最小宽度</div>
                    </template>
                    <span style="display: inline-flex">
                      <span style="margin-right: 5px">列宽</span>
                      <ac-icon iconId="018dca8ec9890493be26" />
                    </span>
                  </el-tooltip>
                </template>
                <template #default="scope">
                  <ac-number v-model="scope.row.width" :point="0" :min="-1000" />
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                label="是否固定列"
                :width="85"
                prop="aliasName"
              >
                <template #default="scope">
                  <ac-dict-switch
                    v-model="scope.row.fixed"
                    dictCode="dictYesNo"
                  />
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                label="是否合并"
                :width="85"
                prop="aliasName"
              >
                <template #default="scope">
                  <ac-dict-switch
                    v-model="scope.row.ifMerge"
                    dictCode="dictYesNo"
                  />
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                label="可否编辑"
                :width="85"
                prop="aliasName"
              >
                <template #default="scope">
                  <ac-dict-switch
                    v-model="scope.row.canEdit"
                    dictCode="dictYesNo"
                  />
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                label="表头对齐方式"
                width="100"
                prop="headerAlign"
              >
                <template #default="scope">
                  <ac-select v-model="scope.row.headerAlign" options="居左,居中,居右" />
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                label="内容对齐方式"
                width="100"
                prop="contentAlign"
              >
                <template #default="scope">
                  <ac-select v-model="scope.row.contentAlign" options="居左,居中,居右" />
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                label="字体颜色"
                width="80"
                prop="contentColor"
              >
                <template #default="scope">
                  <el-color-picker v-model="scope.row.contentColor" :predefine="predefineColors" />
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                label="操作"
                width="110"
                prop="width"
              >
                <template #default="scope">
                  <el-button
                    type="primary"
                    @click="editField(scope.row)"
                    link
                  >设置</el-button>
                  <el-button
                    type="danger"
                    @click="deleteField(scope.row)"
                    link
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane name="ordinal" label="数据排序" class="fit-box full-height">
          <el-row>
            <el-col :span="24" style="margin-bottom: 8px;">
              <el-button
                type="success"
                @click="addOrdinal"
              >添加排序</el-button>
              <el-button
                v-if="sortOrdinalInst"
                type="info"
                @click="unSortDataOrdinal"
              >关闭排序</el-button>
              <el-button
                v-else-if="(formData.ordinalList || []).length > 1"
                type="primary"
                @click="sortDataOrdinal"
              >开启排序</el-button>
            </el-col>
          </el-row>
          <el-table
            ref="sortOrdinalTable"
            :show-overflow-tooltip="false"
            tooltip-effect="light"
            class="field-table fit-table edit-table"
            width="100%"
            :data="formData.ordinalList"
            :row-key="getFieldRowKey"
            :border="true"
            :stripe="false"
          >
            <el-table-column
              header-align="center"
              label="排序字段"
              :min-width="120"
              prop="fieldId"
            >
              <template #default="scope">
                <ac-select v-model="scope.row.fieldId" :options="fieldOptions" />
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="排序方式"
              :min-width="120"
              prop="ordinalMode"
            >
              <template #default="scope">
                <ac-radio v-model="scope.row.ordinalMode" options="升序,降序" />
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="操作"
              :width="80"
            >
              <template #default="scope">
                <el-button
                  type="danger"
                  @click="deleteOrdinal(scope.row)"
                  link
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane
          name="privilege"
          label="权限过滤"
          class="fit-box full-height"
          style="padding-right: 5px;overflow: auto"
        >
          <el-row>
            <el-col :span="24">
              <el-button
                type="success"
                @click="addPrivilege"
              >添加权限组</el-button>
            </el-col>
          </el-row>
          <el-row
            v-for="privilege in formData.privilegeList || []"
            style="margin-top: 15px;"
            :key="privilege.id || privilege.rowFlag"
          >
            <el-col :span="24">
              <el-row>
                <el-col :span="6">
                  <el-form-item label="角色" prop="imageStyle">
                    <ac-role-select showAll v-model="privilege.roleId" />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="排序" prop="ordinal">
                    <ac-number v-model="privilege.ordinal" :point="0" />
                  </el-form-item>
                </el-col>
                <el-col :span="12" style="text-align: right;align-content: center">
                  <el-button
                    v-if="(!sortableInst || sortingId !== (privilege.id || privilege.rowFlag))
                      && (privilege.conditionList || []).length > 1"
                    type="primary"
                    @click="sortPrivilegeField(privilege)"
                  >开启排序</el-button>
                  <el-button
                    v-if="sortableInst && sortingId === (privilege.id || privilege.rowFlag)"
                    type="info"
                    @click="unSortPrivilegeField"
                  >关闭排序</el-button>
                  <el-button
                    type="success"
                    @click="addPrivilegeCondition(privilege)"
                  >添加过滤条件</el-button>
                  <el-button
                    type="danger"
                    @click="deletePrivilege(privilege)"
                  >删除权限组</el-button>
                </el-col>
              </el-row>
              <el-table
                :show-overflow-tooltip="false"
                tooltip-effect="light"
                class="field-table edit-table"
                width="100%"
                :ref="el => setRefs(el, privilege)"
                :row-key="getPrivilegeRowKey"
                :data="privilege.conditionList"
                :border="true"
                :stripe="false"
              >
                <el-table-column
                  header-align="center"
                  label="拼接方式"
                  :min-width="120"
                  prop="connectSymbol"
                >
                  <template #default="scope">
                    <ac-select v-model="scope.row.connectSymbol" options="and,or"/>
                  </template>
                </el-table-column>
                <el-table-column
                  header-align="center"
                  label="前置括号"
                  :min-width="120"
                  prop="frontBracket"
                >
                  <template #default="scope">
                    <ac-select v-model="scope.row.frontBracket" options="(,((,(((,((((" />
                  </template>
                </el-table-column>
                <el-table-column
                  header-align="center"
                  label="过滤字段"
                  :min-width="120"
                  prop="fieldId"
                >
                  <template #default="scope">
                    <ac-select v-model="scope.row.fieldId" :options="fieldOptions" />
                  </template>
                </el-table-column>
                <el-table-column
                  header-align="center"
                  label="比较符"
                  :min-width="120"
                  prop="compareSymbol"
                >
                  <template #default="scope">
                    <ac-select
                      v-model="scope.row.compareSymbol"
                      options="大于,大于等于,等于,小于,小于等于,不等于,模糊"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  header-align="center"
                  label="比较值"
                  :min-width="120"
                  prop="compareValue"
                >
                  <template #header>
                    <span style="margin-right: 5px">比较值</span>
                    <ac-default-value-tips />
                  </template>
                  <template #default="scope">
                    <ac-tree
                      v-if="scope.row.compareSymbol === 'script'"
                      v-model="scope.row.compareValue"
                      data-url="/system/scriptGroovy/queryTree"
                      type-select="script"
                    />
                    <ac-input
                      v-else-if="scope.row.compareSymbol !== 'script' && scope.row.manually === '1'"
                      v-model="scope.row.compareValue"
                    />
                    <component
                      v-else-if="scope.row.compareSymbol !== 'script' && scope.row.fieldId"
                      v-model="scope.row.compareValue"
                      :is="getComponent(scope.row.fieldId) || 'ac-input'"
                      v-bind="getOptions(scope.row.fieldId)"
                    />
                    <el-input v-else v-model="scope.row.compareValue" />
                    <ac-dict-switch
                      v-if="scope.row.compareSymbol !== 'script'"
                      v-model="scope.row.manually"
                      dictCode="dictYesNo"
                      style="margin: 0 5px;"
                      title="手动录入"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  header-align="center"
                  label="后置括号"
                  :min-width="120"
                  prop="behindBracket"
                >
                  <template #default="scope">
                    <ac-select v-model="scope.row.behindBracket" options="),)),))),))))" />
                  </template>
                </el-table-column>
                <el-table-column
                  header-align="center"
                  align="center"
                  label="操作"
                  :min-width="80"
                  prop="ordinal"
                >
                  <template #default="scope">
                    <el-button
                      type="danger"
                      @click="deletePrivilegeCondition(privilege, scope.row)"
                      link
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane name="tips" label="提示信息" class="fit-box full-height">
          <el-row>
            <el-col :span="6">
              <el-form-item label="位置" prop="tipsPosition" label-width="80">
                <ac-buttons v-model="formData.tipsPosition" options="顶部,底部" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="来源" prop="tipsOrigin" label-width="80">
                <ac-buttons v-model="formData.tipsOrigin" options="输入,脚本" />
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="formData.tipsOrigin === '脚本'">
              <el-form-item label="脚本" prop="tipsScriptId" label-width="80">
                <ac-tree
                  v-model="formData.tipsScriptId"
                  data-url="/system/scriptGroovy/queryTree"
                  type-select="script"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <ac-rich-editor v-if="formData.tipsOrigin === '输入'" v-model="formData.tipsHtml" />
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </div>

  <!-- 合计栏设置 -->
  <el-dialog
    v-model="totalVisible"
    width="650px"
    title="合计栏设置"
    :close-on-click-modal="false"
    destroy-on-close
    append-to-body
    draggable
  >
    <el-form
      ref="totalForm"
      label-width="120px"
      :model="totalData"
      :rules="totalRules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="表尾合计" prop="showSummary">
            <ac-dict-radio v-model="totalData.showSummary" dictCode="dictYesNo" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="totalData.showSummary === '1'">
        <el-col :span="24">
          <el-form-item label="显示合计列" prop="summaryFieldId">
            <el-select v-model="totalData.summaryFieldId">
              <el-option
                v-for="field in fieldList"
                :key="field.id"
                :label="field.fieldName"
                :value="field.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="totalData.showSummary === '1'">
        <el-col :span="24">
          <el-form-item label="合计名称" prop="summaryName">
            <el-input v-model="totalData.summaryName" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="totalData.showSummary === '1'">
        <el-col :span="24">
          <el-form-item label="合计字段" prop="summaryFieldIds">
            <el-checkbox-group v-model="totalData.summaryFieldIds">
              <el-checkbox
                v-for="field in fieldList"
                :key="field.id"
                :label="field.fieldName"
                :value="field.id"
              />
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="totalVisible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        @click="submitTotal"
      >确定</el-button>
    </template>
  </el-dialog>

  <!-- 添加字段 -->
  <el-dialog
    v-model="fieldAddVisible"
    title="添加字段"
    class="no-padding"
    :close-on-click-modal="false"
    destroy-on-close
    fullscreen
    draggable
  >
    <div class="page-container">
      <el-table
        ref="fieldAddTable"
        :show-overflow-tooltip="false"
        tooltip-effect="light"
        class="field-table fit-table"
        width="100%"
        @row-click="rowClick"
        :data="fieldList"
        :border="true"
        :stripe="false"
      >
        <el-table-column
          header-align="center"
          align="center"
          type="selection"
          width="55"
        />
        <el-table-column
          header-align="center"
          label="字段名称"
          :min-width="120"
          prop="fieldName"
        />
        <el-table-column
          header-align="center"
          label="显示名称"
          :min-width="120"
          prop="showName"
        />
        <el-table-column
          header-align="center"
          align="center"
          label="是否主键"
          :width="100"
          prop="primaryKey"
        >
          <template #default="scope">
            <ac-dict-radio showText v-model="scope.row.primaryKey" dictCode="dictYesNo" />
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="字段类型"
          :width="120"
          prop="fieldType"
        />
        <el-table-column
          header-align="center"
          align="center"
          label="是否必填"
          :width="100"
          prop="required"
        >
          <template #default="scope">
            <ac-dict-radio showText v-model="scope.row.required" dictCode="dictYesNo" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="fieldAddVisible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        @click="submitFieldAddForm"
      >确定</el-button>
    </template>
  </el-dialog>

  <!-- 编辑字段 -->
  <el-dialog
    v-model="fieldVisible"
    width="850px"
    style="height: 610px"
    title="字段编辑"
    class="no-padding"
    :close-on-click-modal="false"
    destroy-on-close
    draggable
  >
    <div class="page-container">
      <el-form
        ref="fieldForm"
        label-width="130px"
        :model="fieldData"
        :rules="fieldRules"
        style="height: 100%;"
      >
        <el-tabs v-model="fieldTabName">
          <el-tab-pane name="field" label="基础信息">
            <el-row>
              <el-col :span="11">
                <el-form-item label="字段名称" prop="fieldName">
                  <el-input
                    v-model="fieldData.fieldName"
                    auto-complete="off"
                    :disabled="true"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="显示名称" prop="aliasName">
                  <el-input v-model="fieldData.aliasName"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="表头对齐方式" prop="headerAlign">
                  <ac-buttons v-model="fieldData.headerAlign" options="居左,居中,居右"
                  ></ac-buttons>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="内容对齐方式" prop="contentAlign">
                  <ac-buttons v-model="fieldData.contentAlign" options="居左,居中,居右"
                  ></ac-buttons>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="列宽" prop="width">
                  <ac-number v-model="fieldData.width" :point="0" :min="-1000" />
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="字体颜色" prop="contentColor">
                  <el-color-picker v-model="fieldData.contentColor" :predefine="predefineColors" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="是否合并" prop="ifMerge">
                  <ac-dict-switch
                    v-model="fieldData.ifMerge"
                    dictCode="dictYesNo"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="自动换行" prop="wrap">
                  <ac-dict-switch
                    v-model="fieldData.wrap"
                    dictCode="dictYesNo"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="是否固定列" prop="fixed">
                  <ac-dict-switch
                    v-model="fieldData.fixed"
                    dictCode="dictYesNo"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="可否编辑" prop="canEdit">
                  <ac-dict-switch
                    v-model="fieldData.canEdit"
                    dictCode="dictYesNo"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane name="style" label="样式设置">
            <div style="margin-bottom: 8px">
              <el-button type="success" @click="addDataTableFieldStyle()">添加</el-button>
            </div>
            <el-table
              ref="sortTable"
              element-loading-text="数据加载中..."
              :show-overflow-tooltip="false"
              class="field-table edit-table"
              width="100%"
              :data="fieldData.styleList"
              :border="true"
              :stripe="false"
            >
              <el-table-column
                header-align="center"
                label="匹配值"
                :min-width="100"
                prop="originValue"
              >
                <template #header>
                  <el-tooltip>
                    <template #content>
                      <div>
                        <span
                          style="cursor: pointer"
                          @click="copySymbol('{all}')"
                        >{all}</span>: 匹配所有值
                      </div>
                    </template>
                    <span style="display: inline-flex">
                        <span style="margin-right: 5px">匹配值</span>
                        <ac-icon iconId="018dca8ec9890493be26" />
                      </span>
                  </el-tooltip>
                </template>
                <template #default="scope">
                  <el-input v-model="scope.row.originValue" />
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                label="显示类型"
                width="100"
                prop="showType"
              >
                <template #default="scope">
                  <ac-select
                    v-model="scope.row.showType"
                    options="文字,标签,图形,时间,时长,进度条,js脚本"
                  />
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                label="显示颜色"
                width="70"
                prop="showColor"
              >
                <template #default="scope">
                  <el-color-picker v-model="scope.row.showColor" :predefine="predefineColors" />
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                label="是否闪烁"
                width="70"
                prop="flash"
              >
                <template #default="scope">
                  <ac-dict-switch
                    v-model="scope.row.flash"
                    dictCode="dictYesNo"
                  />
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                label="显示值"
                :min-width="100"
                prop="targetValue"
              >
                <template #header>
                  <el-tooltip>
                    <template #content>
                      <div>显示类型为【文字】时的：
                        <span
                          style="cursor: pointer"
                          @click="copySymbol('{currValue}')"
                        >{currValue}</span> 为当前值
                      </div>
                      <div>显示类型为【时长】时格式化成：x 天 x 小时 x 分 x 秒，单位为毫秒</div>
                      <div>显示类型为【进度条】时的：
                        <span
                          style="cursor: pointer"
                          @click="copySymbol('{currValue}')"
                        >{currValue}</span> 为当前值
                      </div>
                      <div>&nbsp;&nbsp;示例：
                        <span
                          style="cursor: pointer"
                          @click="copySymbol('{currValue}*100')"
                        >{currValue}*100</span> 为进度条的百分比值
                      </div>
                      <div>显示类型为【js脚本】时的参数获取方式：</div>
                      <div>&nbsp;
                        <span
                          style="cursor: pointer"
                          @click="copySymbol('args.data')"
                        >args.data</span>：当前行数据
                      </div>
                      <div>&nbsp;
                        <span
                          style="cursor: pointer"
                          @click="copySymbol('args.user')"
                        >args.user</span>：当前登录用户信息
                      </div>
                      <div>&nbsp;
                        <span
                          style="cursor: pointer"
                          @click="copySymbol('args.org')"
                        >args.org</span>：当前登录用户组织机构信息
                      </div>
                      <div>
                        &nbsp;&nbsp;示例：
                        <span
                          style="cursor: pointer"
                          @click="copySymbol(jsDemo)"
                        >{{jsDemo}}</span>
                      </div>
                    </template>
                    <span style="display: inline-flex">
                        <span style="margin-right: 5px">显示值</span>
                        <ac-icon iconId="018dca8ec9890493be26" />
                      </span>
                  </el-tooltip>
                </template>
                <template #default="scope">
                  <ac-select
                    v-if="scope.row.showType === '图形'"
                    v-model="scope.row.targetValue"
                    options="圆形,正方形,椭圆形"
                  />
                  <ac-input
                    v-else
                    :type="scope.row.showType === 'js脚本' ? 'textarea' : 'text'"
                    v-model="scope.row.targetValue"
                  />
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                label="操作"
                :width="60"
                fixed="right"
              >
                <template #default="scope">
                  <el-button
                    type="danger"
                    @click="deleteDataTableFieldStyle(scope.row)"
                    link
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane name="link" label="页面关联">
            <el-row>
              <el-col :span="22">
                <el-form-item label="页面名称" prop="pageId">
                  <ac-tree
                    v-model="fieldData.pageId"
                    data-url="/system/page/queryTree"
                    typeSelect="page"
                    @change="changePage"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="fieldData.pageId && fieldData.paramList && fieldData.paramList.length > 0">
              <el-col :span="22">
                <el-form-item
                  v-if="fieldData.paramList && fieldData.paramList.length > 0"
                  label="出参配置"
                  prop="pageId"
                >
                  <div style="display: flex;flex-direction: column">
                    <div
                      class="param-item"
                      v-for="(param, index) in fieldData.paramList"
                      :key="index"
                    >
                      <div class="param-field">
                        <ac-select
                          v-model="param.fieldId"
                          :options="fieldOptions"
                          allow-create
                        />
                      </div>
                      <div class="param-split"><ac-icon iconId="018eecae20bd010c2adf" /></div>
                      <div class="param-page">
                        <el-input v-model="param.pageParamName" disabled />
                      </div>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="22">
                <el-form-item label="显示关联图标" prop="showRelevanceIcon">
                  <ac-dict-switch
                    v-model="fieldData.showRelevanceIcon"
                    dictCode="dictYesNo"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="全屏弹窗" prop="fullscreenDialog">
                  <ac-dict-switch v-model="fieldData.fullscreenDialog" dictCode="dictYesNo" />
                </el-form-item>
              </el-col>
              <el-col :span="11" v-if="fieldData.fullscreenDialog !== '1'">
                <el-form-item label="弹窗大小" prop="dialogWidth">
                  <ac-number v-model="fieldData.dialogWidth" :point="0" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="显示关闭按钮" prop="showCloseButton">
                  <ac-dict-switch v-model="fieldData.showCloseButton" dictCode="dictYesNo" />
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="关闭后刷新" prop="closeRefresh">
                  <ac-dict-switch v-model="fieldData.closeRefresh" dictCode="dictYesNo" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="打开前执行脚本" prop="openScriptId">
                  <ac-tree
                    v-model="fieldData.openScriptId"
                    data-url="/system/scriptGroovy/queryTree"
                    typeSelect="script"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="关闭后执行脚本" prop="closeScriptId">
                  <ac-tree
                    v-model="fieldData.closeScriptId"
                    data-url="/system/scriptGroovy/queryTree"
                    typeSelect="script"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="22">
                <el-form-item label="显示执行结果" prop="showExecuteResult">
                  <ac-dict-switch v-model="fieldData.showExecuteResult" dictCode="dictYesNo" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="fieldVisible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        @click="submitFieldForm"
      >确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import clipboard from 'clipboard';
import api from "@/http/api";
import { ElMessage, ElMessageBox } from "element-plus";
import Sortable from 'sortablejs';
import tool from "@/utils/tool";
import loading from '@/utils/loading';

const emit = defineEmits(['afterSubmit'])
const props = defineProps({
  options: {
    type: Object,
    default: () => {}
  }
});
const predefineColors = ref([
  '#409EFF',
  '#67C23A',
  '#E6A23C',
  '#F56C6C',
  '#909399',
  '#ff4500',
  '#ff8c00',
  '#ffd700',
  '#90ee90',
  '#00ced1',
  '#1e90ff',
  '#c71585',
  '#FF7800',
]);

const tabName = ref('table');
const sortFieldTable = ref();
const sortFieldInst = ref();
const formData = ref({});
const dataForm = ref();
const fieldList = ref([]);
const fieldOptions = ref([]);

const totalVisible = ref(false);
const totalForm = ref();
const totalData = ref({});

const fieldTabName = ref('field');
const fieldVisible = ref(false);
const fieldForm = ref();
const fieldData = ref({});
const fieldRules = ref({});

const fieldAddVisible = ref(false);
const fieldAddTable = ref();
const rowFlag = ref(0);

const sortOrdinalTable = ref();
const sortOrdinalInst = ref();

const privilegeRefs  = ref([]);
const sortingId = ref();
const sortableInst = ref();
const jsDemo =  ref("return '<div " +
    "style=\"cursor: pointer\" " +
    "onclick=\"window.open(\\'http://www.baidu.com?id=' + args.data.id + '\\', \\'_blank\\')\"" +
  ">' + args.data.name + '</div>';");

const rules = ref({
  name: [
    {required: true, message: '请输入名称', trigger: ['change', 'blur']},
    {max: 100, message: '长度必须小于等于 200 个字符！', trigger: ['change', 'blur']}
  ],
  defaultPageSize: [
    {required: true, message: '请选择默认分页大小', trigger: ['change', 'blur']},
  ],
});
const totalRules = ref({
  showSummary: [
    {required: true, message: '请选择表尾合计', trigger: ['change', 'blur']},
  ],
  summaryFieldId: [
    {required: true, message: '请选择显示合计列', trigger: ['change', 'blur']},
  ],
  summaryName: [
    {required: true, message: '请输入合计名称', trigger: ['change', 'blur']},
  ],
  summaryFieldIds: [
    {required: true, message: '请选择合计字段', trigger: ['change', 'blur']},
  ],
});

const component = ref({
  '单行文本框': 'ac-input',
  '密码文本框': 'ac-password',
  '多行文本框': 'ac-input',
  '富文本框': 'ac-input',
  '单选框': 'ac-select',
  '下拉框': 'ac-select',
  '开关': 'ac-switch',
  '字符': 'ac-input',
  '整数': 'ac-number',
  '小数': 'ac-number',
  '日期': 'ac-date',
  '时间': 'ac-datetime',
  '图片': 'ac-image',
  '视频': 'ac-video',
  '附件': 'ac-affix',
  '下拉选择': 'ac-remote-select',
  '树形控件': 'ac-dm-tree',
  '区划树': 'ac-region-tree',
  '单位树': 'ac-unit-tree',
  '企业树': 'ac-entp-tree',
  '部门树': 'ac-organization-tree',
  '人员树': 'ac-employee-tree',
  '字典树': 'ac-dm-tree',
  '字典开关': 'ac-dict-switch',
  '字典单选框': 'ac-dict-select',
  '字典下拉框': 'ac-dict-select',
});
const getComponent = (fieldId) => {
  if (!fieldId) return;

  const field = fieldList.value.find(item => item.id === fieldId);
  if (!field) return 'ac-input';

  if (field.fieldType === '字符') {
    if (field.enumerate === '1') {
      return component.value[field.enumerateType];
    } else {
      return component.value[field.inputType];
    }
  } else if ("整数、小数、日期、时间、图片、视频、附件".indexOf(field.fieldType) >= 0) {
    return component.value[field.fieldType];
  } else if (field.fieldType === '联动') {
    if (field.relevanceType === '数据模型') {
      return component.value['树形控件'];
    } else {
      return component.value[field.relevanceType];
    }
  } else if (field.fieldType === '大文本') {
    return component.value[field.inputType];
  }

  return 'ac-input';
};

const getOptions = (fieldId) => {
  if (!fieldId) return;

  const field = fieldList.value.find(item => item.id === fieldId);
  if (!field) return {};

  if (field.fieldType === '字符') {
    if (field.autoCreate === '1') {
      return {};
    } else if (field.enumerate === '1') {
      return {options: field.enumerateValue || '', allowCreate: true};
    } else {
      return {max: field.fieldSize || 100};
    }
  } else if ("整数、小数".indexOf(field.fieldType) >= 0) {
    return {
      point: "整数" === field.fieldType ? 0 : field.fieldPrecision || 0,
      max: field.maxValue, min: field.minValue
    };
  } else if ("日期".indexOf(field.fieldType) >= 0) {
    return {format: field.format || undefined, valueFormat: field.format || undefined};
  } else if (field.fieldType === '图片') {
    return {limit: 1, maxSize: field.imageMaxSize};
  } else if (field.fieldType === '视频') {
    return {limit: 1, maxSize: field.imageMaxSize};
  } else if (field.fieldType === '联动') {
    if (field.relevanceType === '数据模型') {
      const relevanceList = field.relevanceList || [];
      return {
        dataFieldId: field.id,
        leafSelect: relevanceList.length > 1,
        typeSelect: relevanceList[relevanceList.length - 1].id
      };
    } else {
      return {dictCode: field.relevanceDict || ''};
    }
  }

  return {};
};

const getFieldRowKey = row => {
  return row.id || row.rowFlag;
};

const sortDataField = () => {
  if (sortFieldInst.value) {
    sortFieldInst.value.destroy();
  }

  if (sortFieldTable.value) {
    const el = sortFieldTable.value.$el.querySelector(".el-table__body-wrapper tbody");
    sortFieldInst.value = Sortable.create(el, {
      handle: '.el-table__row',
      onEnd: ({ newIndex, oldIndex}) => {
        const list = tool.deepClone(formData.value.fieldList);
        const currRow = list.splice(oldIndex, 1)[0];
        list.splice(newIndex, 0, currRow);
        nextTick(() => {
          formData.value.fieldList = list;
        });
      }
    });
  }
};

const unSortDataField = () => {
  if (sortFieldInst.value) {
    sortFieldInst.value.destroy();
  }
  sortFieldInst.value = null;
};

const getPrivilegeRowKey = row => {
  return row.id || row.rowFlag;
};

const setRefs = (el, privilege) => {
  if (el) {
    privilegeRefs.value['privilegeTable_' + (privilege.id || privilege.rowFlag)] = el;
  }
};

const sortPrivilegeField = (privilege) => {
  if (sortableInst.value) {
    sortableInst.value.destroy();
  }

  const ref = privilegeRefs.value['privilegeTable_' + (privilege.id || privilege.rowFlag)];
  if (ref) {
    const el = ref.$el.querySelector(".el-table__body-wrapper tbody");
    sortableInst.value = Sortable.create(el, {
      handle: '.el-table__row',
      onEnd: ({ newIndex, oldIndex}) => {
        const list = tool.deepClone(privilege.conditionList);
        const currRow = list.splice(oldIndex, 1)[0];
        list.splice(newIndex, 0, currRow);
        nextTick(() => {
          privilege.conditionList = list;
        });
      }
    });
    sortingId.value = privilege.id || privilege.rowFlag;
  }
};

const unSortPrivilegeField = () => {
  if (sortableInst.value) {
    sortableInst.value.destroy();
  }
  sortableInst.value = null;
};

const sortDataOrdinal = () => {
  if (sortOrdinalInst.value) {
    sortOrdinalInst.value.destroy();
  }

  if (sortOrdinalTable.value) {
    const el = sortOrdinalTable.value.$el.querySelector(".el-table__body-wrapper tbody");
    sortOrdinalInst.value = Sortable.create(el, {
      handle: '.el-table__row',
      onEnd: ({ newIndex, oldIndex}) => {
        const list = tool.deepClone(formData.value.ordinalList);
        const currRow = list.splice(oldIndex, 1)[0];
        list.splice(newIndex, 0, currRow);
        nextTick(() => {
          formData.value.ordinalList = list;
        });
      }
    });
  }
};

const unSortDataOrdinal = () => {
  if (sortOrdinalInst.value) {
    sortOrdinalInst.value.destroy();
  }
  sortOrdinalInst.value = null;
};

const init = (options) => {
  formData.value = {
    id: options.id || '',
    modelId: options.modelId || '',
    name: '',
    showHeader: '1',
    showHeaderSetting: '1',
    showFull: '1',
    showCheckbox: '1',
    showOrdinal: '1',
    showOperate: '1',
    showPagination: '1',
    showBorder: '1',
    totalJson: "",
    defaultPageSize: '20',
    defaultTable: "0",
    fieldList: []
  };
  loadDataTable(options.id);
  loadDataField(options.modelId);
};

const rowClick = (row) => {
  fieldAddTable.value.toggleRowSelection(row);
};

const showTotalDialog = () => {
  totalVisible.value = true;
  if (formData.value.totalJson && formData.value.totalJson.startsWith("{")) {
    totalData.value = JSON.parse(formData.value.totalJson);
  } else {
    totalData.value = {
      showSummary: '1',
      summaryName: '合计'
    };
  }
};

const submitTotal = () => {
  totalForm.value.validate(valid => {
    if (!valid) return;

    if (totalData.value.showSummary !== '1') {
      formData.value.totalJson = '';
    } else {
      formData.value.totalJson = JSON.stringify(totalData.value);
    }
    totalVisible.value = false;
  });
};

const addField = () => {
  fieldAddVisible.value = true;
  nextTick(() => {
    formData.value.fieldList.forEach(field => {
      const row = fieldList.value.find(item => item.id === field.fieldId);
      if (row) {
        fieldAddTable.value.toggleRowSelection(row, true);
      }
    });
  });
};

const submitFieldAddForm = () => {
  fieldAddTable.value.getSelectionRows().forEach(row => {
    if (formData.value.fieldList.findIndex(item => item.fieldId === row.id) < 0) {
      const data = tool.deepClone(row);
      data.id = null;
      data.rowFlag = ++rowFlag.value;
      data.fieldId = row.id;
      data.fieldName = row.fieldName;
      data.aliasName = row.showName;
      data.width = row.fieldName === 'update_time' || row.fieldName === 'create_time' ? 165 : 120;
      data.ifMerge = '0';
      data.wrap = '0';
      data.headerAlign = "居中";
      data.contentAlign = "居左";
      formData.value.fieldList.push(data);
    }
  });
  fieldAddVisible.value = false;
};

const editField = (data) => {
  fieldTabName.value = 'field';
  fieldData.value = tool.deepClone(data);
  fieldData.value.showCloseButton = fieldData.value.showCloseButton || '1';
  if (fieldData.value.pageFieldJson) {
    fieldData.value.paramList = JSON.parse(fieldData.value.pageFieldJson);
  }
  changePage();
  fieldVisible.value = true;
};

const changePage = () => {
  if (!fieldData.value.pageId) {
    fieldData.value.paramList = [];
    return;
  }

  api.post('/system/pageParam/queryList', {pageId: fieldData.value.pageId}).then(res => {
    const pageParamList = res.data || [];
    const paramList = fieldData.value.paramList;
    pageParamList.forEach(pageParam => {
      const fieldParam = paramList.find(item => item.pageParamId === pageParam.id);
      if (fieldParam) {
        fieldParam.pageParamName = pageParam.name;
      } else {
        paramList.push({pageParamId: pageParam.id, pageParamName: pageParam.name});
      }
    });

    fieldData.value.paramList = paramList.filter(param => pageParamList.find(item => item.id === param.pageParamId));
  });
};

const fieldFlag = ref(1);
const addDataTableFieldStyle = () => {
  if (!fieldData.value.styleList) {
    fieldData.value.styleList = [];
  }

  fieldData.value.styleList.push({
    fieldFlag: ++fieldFlag.value,
    showType: '文字',
    flash: '0',
  });
};

const deleteDataTableFieldStyle = (data) => {
  ElMessageBox.confirm('请确认是否删除？', '提示', {type: 'warning'}).then(() => {
    const index = fieldData.value.styleList.findIndex(item =>
      (data.id && item.id === data.id) || (item.fieldFlag > 0 && item.fieldFlag === data.fieldFlag));
    fieldData.value.styleList.splice(index, 1);
  }).catch(() => {});
};

const submitFieldForm = () => {
  if (fieldData.value.pageId && fieldData.value.paramList) {
    fieldData.value.pageFieldJson = JSON.stringify(
      fieldData.value.paramList.map(param => {
        const field = fieldList.value.find(item => item.id === param.fieldId);
        return {
          fieldId: param.fieldId,
          fieldName: field ? field.fieldName : '',
          pageParamId: param.pageParamId,
          pageParamName: param.pageParamName
        }
      }));
  } else {
    fieldData.value.pageFieldJson = '';
  }
  const data = fieldData.value;
  const index = formData.value.fieldList
    .findIndex(item => data.id ? item.id === data.id : item.rowFlag === data.rowFlag);
  formData.value.fieldList[index] = data;

  fieldData.value = {};
  fieldVisible.value = false;
};

const deleteField = (data) => {
  ElMessageBox.confirm('请确认是否删除【' + data.aliasName + '】？', '提示', {type: 'warning'}).then(() => {
    const index = formData.value.fieldList
      .findIndex(item => data.id ? item.id === data.id : item.rowFlag === data.rowFlag);
    formData.value.fieldList.splice(index, 1);
  });
};

const addOrdinal = () => {
  if (!formData.value.ordinalList) {
    formData.value.ordinalList = [];
  }

  formData.value.ordinalList.push({rowFlag: ++rowFlag.value});
};

const deleteOrdinal = (data) => {
  ElMessageBox.confirm('请确认是否删除？', '提示', {type: 'warning'}).then(() => {
    const index = formData.value.ordinalList
      .findIndex(item => item.id ? item.id === data.id : item.rowFlag === data.rowFlag);
    formData.value.ordinalList.splice(index, 1);
  });
}

const addPrivilege = () => {
  if (!formData.value.privilegeList) {
    formData.value.privilegeList = [];
  }

  formData.value.privilegeList.push({
    roleId: '',
    rowFlag: ++rowFlag.value,
    conditionList: [{}]
  });
};

const deletePrivilege = (privilege) => {
  ElMessageBox.confirm('请确认是否删除？', '提示', {type: 'warning'}).then(() => {
    const index = formData.value.privilegeList
      .findIndex(item => privilege.id ? item.id === privilege.id : item.rowFlag === privilege.rowFlag);
    formData.value.privilegeList.splice(index, 1);
  });
};

const addPrivilegeCondition = (privilege) => {
  privilege.conditionList.push({rowFlag: ++rowFlag.value});
};

const deletePrivilegeCondition = (privilege, data) => {
  ElMessageBox.confirm('请确认是否删除？', '提示', {type: 'warning'}).then(() => {
    const index = privilege.conditionList
      .findIndex(item => item.id ? item.id === data.id : item.rowFlag === data.rowFlag);
    privilege.conditionList.splice(index, 1);
  });
};

const loadDataTable = (id) => {
  if (id) {
    loading.showLoading();
    api.post('/system/dataTable/queryBy', {id: id}).then(res => {
      const data = res.data || {};
      data.defaultPageSize = (data.defaultPageSize || '') + '';
      formData.value = data;
      loading.hideLoading();
    }).catch(() => loading.hideLoading());
  }
};

const loadDataField = (modelId) => {
  fieldOptions.value = [];

  api.post('/system/dataField/queryList', {modelId: modelId}).then(res => {
    fieldList.value = res.data || [];
    fieldList.value.forEach(field => {
      fieldOptions.value.push({key: field.id, value: field.showName});
    });
  });
};

const submitData = () => {
  if (formData.value.ordinalList && formData.value.ordinalList.length > 0) {
    for (let i=0; i<formData.value.ordinalList.length; i++) {
      const ordinal = formData.value.ordinalList[i];
      if (!ordinal.fieldId) {
        ElMessage.error("数据排序 / 排序字段 不能为空！");
        return;
      }
    }
  }

  if (formData.value.privilegeList && formData.value.privilegeList.length > 0) {
    for (let privilege of formData.value.privilegeList) {
      for (let i=0; i<privilege.conditionList.length; i++) {
        const condition = privilege.conditionList[i];
        if (i > 0 && !condition.connectSymbol) {
          ElMessage.error("权限过滤 / 拼接方式 不能为空！");
          return;
        }
        if (!condition.fieldId) {
          ElMessage.error("权限过滤 / 过滤字段 不能为空！");
          return;
        }
        if (!condition.compareSymbol) {
          ElMessage.error("权限过滤 / 比较符 不能为空！");
          return;
        }
      }
    }
  }

  dataForm.value && dataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm("请确认是否提交？", "提示", { type: "info" }).then(() => {
        loading.showLoading();
        api.post('/system/dataTable/save', formData.value).then(res => {
          ElMessage.success(res.message);
          emit('afterSubmit');
          loading.hideLoading();
        }).catch(() => loading.hideLoading());
      });
    } else {
      ElMessage.error("数据录入不正确，请重新检查！");
    }
  });
};

const copySymbol = (symbol) => {
  clipboard.copy(symbol);
  ElMessage.success("已复制到剪贴板");
};

watch(() => props.options, (options) => {
  init(options || {});
});

onMounted(() => {
  init(props.options || {});
});

onUnmounted(() => {
  unSortDataField();
  unSortDataOrdinal();
});

defineExpose({ submitData });
</script>

<style scoped lang="scss">
.radio-span {
  padding: 0 5px;
  :deep(.el-radio) {
    margin-right: 10px;
  }
}
.param-item {
  display: flex;
  flex-direction: row;
  .param-field {
    width: 175px;
  }
  .param-split {
    width: 44px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
  }
  .param-page {
    flex-grow: 1;
  }
}
.param-item+.param-item {
  margin-top: 5px;
}
</style>